'use client';

import Modal from "@/components/ui/Modal/Modal";
import AddVehicleForm from "@/components/ui/Forms/AddTransportForm/AddVehicleForm";
import ClientTicketForm from "@/components/ui/Forms/ClientTicketForm/ClientTicketForm";
import {useEffect, useState} from "react";
import {getObj} from "@/services/api_service";
import styles from "./UserPage.module.css";
import Image from "next/image";
import Button from "@/components/ui/Button/Button";

export default function UserPage() {
    const [modalOpen, setModalOpen] = useState(false);
    const [addVehicleActive, setAddVehicleActive] = useState(false);
    const [addTicketActive, setAddTicketActive] = useState(false);

    const [userData, setUserData] = useState<any>(null);

    useEffect(() => {
        if (addVehicleActive && !modalOpen) {
            const timeout = setTimeout(() => {
                setAddVehicleActive(false);
            }, 200);
            return () => {
                clearTimeout(timeout);
            };
        }

        if (addTicketActive && !modalOpen) {
            const timeout = setTimeout(() => {
                setAddTicketActive(false);
            }, 200);
            return () => {
                clearTimeout(timeout);
            };
        }
    }, [modalOpen]);

    useEffect(() => {
        const getUserData = async () => {
            try {
                const userData = await getObj('/api/auth/get-user-data/');
                setUserData(userData);
            } catch (error) {
                console.error('Ошибка при получении данных пользователя:', error);
            }
        };
        getUserData();

    }, []);

    const DateOptions: Intl.DateTimeFormatOptions = {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
    };

    return (
        <>
            <div className={styles.container}>
                <header className={styles.header}>
                    <h1>Личный кабинет</h1>
                </header>

                <div className={styles.userInfo}>
                    <h2>Основная информация</h2>
                    <p><strong>Email:</strong> {userData?.user?.email}</p>
                    {userData?.vehicles && userData.vehicles.length > 0 && (
                        <div className={styles.vehicleInfo}>
                            <h3>Транспортное средство</h3>
                            {userData.vehicles.map((vehicle: any) => (
                                <div key={vehicle.id}>
                                    <p><strong>Регистрационный номер:</strong> {vehicle.registration_number}</p>
                                    <p><strong>Тип:</strong> {vehicle.vehicle_type}</p>
                                </div>
                            ))}
                        </div>
                    )}
                    {userData?.active_tickets && userData.active_tickets.length > 0 && (
                        <div className={styles.ticketInfo}>
                            <h3>Действующий билет</h3>
                            {userData.active_tickets.map((ticket: any) => (
                                <div key={ticket.id}>
                                    <p>
                                        <strong>Маршрут:</strong> {ticket.departure_port_name} - {ticket.arrival_port_name}
                                    </p>
                                    <p><strong>Тип билета:</strong> {ticket.ticket_type_name}</p>
                                    <p>
                                        <strong>Действителен
                                            с:</strong> {new Date(ticket.valid_from).toLocaleString("ru-RU", DateOptions)}
                                        <strong> до:</strong> {new Date(ticket.valid_to).toLocaleString("ru-RU", DateOptions)}
                                    </p>
                                    {ticket.qr_code && (
                                        <div className={styles.qrCode}>
                                            <Image src={`${process.env.NEXT_PUBLIC_API_HOST}${ticket.qr_code}`}
                                                   width={150} height={150} alt="QR код билета"/>
                                        </div>
                                    )}
                                </div>
                            ))}
                        </div>
                    )}
                </div>

                <div className={styles.buttons_container}>
                    {!userData?.vehicles && (
                        <Button type="button" kind="submit" content="Добавить транспорт" onClick={() => {
                            setAddVehicleActive(true);
                            setModalOpen(true);
                        }}/>)}
                    <Button type="button" kind="submit" content="Купить билет" onClick={() => {
                        setAddTicketActive(true);
                        setModalOpen(true);
                    }}/>
                </div>
            </div>

            {addVehicleActive && (
                <Modal headText={'Добавление транспорта'}
                       modalOpen={modalOpen} setModalOpen={setModalOpen}>
                    <AddVehicleForm/>
                </Modal>
            )}

            {addTicketActive && (
                <Modal headText={'Покупка билета'}
                       modalOpen={modalOpen} setModalOpen={setModalOpen}>
                    <ClientTicketForm setModalOpen={setModalOpen}/>
                </Modal>
            )}
        </>
    );
}
